'use strict';
const Sequelize = require('sequelize');
const Service = require('egg').Service;
const Op = Sequelize.Op;
const { ErrCode } = require('../../utils/resModel');

class UserService extends Service {
  //获取7天访问量
  async visitnum() {
    try {
      const { User } = this.app.model.Tables.Shop;
      const query = this.ctx.query;
      // 每页多少条
      const limit = parseInt(query.limit) || 10;
      // 页数
      const page = parseInt(query.page) || 1;
      // 页数 * 每页个数
      const offset = limit * (page - 1);
      let datalist = [];
      for (let i = 1; i < 8; i++) {
        let after_time = Date.now() + 24 * 3600 * 1000;
        let after = new Date(after_time).toISOString();
        let before_time = after_time - i * (24 * 3600 * 1000);
        let before = new Date(before_time).toISOString();
        let start = before;
        let end = after;
        const where = {
          createdAt: {
            [Op.between]: [start, end],
          },
          project_id: query.project_id,
        };
        const result = await User.findAll({
          limit,
          offset,
          order: [['visit_num', 'DESC']],
          where,
          distinct: true,
        });
        if (result) {
          const data = JSON.parse(JSON.stringify(result));
          let visit_total = 0;
          data.forEach((ele) => {
            let visit_list = ele.visit_num;
            visit_total += visit_list - 0;
          });
          // let key = "visit_total"
          // let value = visit_total
          // data[key] = value
          let dataobj = { date: before, num: visit_total };
          datalist.push(dataobj);
          // console.log('this is visit_total===>', visit_total);
          // console.log('this is data===>', data);

          // return this.ctx.response.success(result, '获取成功');
        }
      }
      return this.ctx.response.success(datalist);
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 获取自己用户信息
  async userInfo() {
    try {
      const { User } = this.app.model.Tables.Shop;
      const result = await User.findOne({
        where: {
          id: this.ctx.userInfo.id,
        },
        attributes: {
          exclude: ['password'],
        },
      });
      // 访问量+ 1
      let j = 0;
      const obj = result;
      while (j == 0) {
        // console.log('result.dataValues ===>', result.dataValues);
        // console.log('obj[result.dataValues.id] ==>', obj.id);
        await result.update({
          id: obj.id,
          visit_num: result.dataValues.visit_num + 1,
        });
        j++;
      }

      if (result) {
        return this.ctx.response.success(result);
      }
      return this.ctx.response.error('找不到该用户信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 获取用户列表信息
  async index() {
    try {
      const { User } = this.app.model.Tables.Shop;
      const result = await User.findAll();
      if (result) {
        return this.ctx.response.success(result);
      }
      return this.ctx.response.error('获得用户列表信息失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 获取单个用户
  async show(id) {
    try {
      const { User } = this.app.model.Tables.Shop;

      const result = await User.findOne({
        where: {
          id,
        },
      });
      if (result) {
        return this.ctx.response.success(result);
      }
      return this.ctx.response.error('找不到该用户信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 更新用户信息
  async update(id, data) {
    try {
      const { User } = this.app.model.Tables.Shop;

      const resultUser = await User.findByPk(id);
      if (resultUser && resultUser.dataValues) {
        if(data.password) data.password = await this.ctx.genHash(String(data.password));
        const result = (await resultUser.update({ ...data })).toJSON();
        delete result.password;
        delete result.token;
        delete result.token_out_of_date;

        return this.ctx.response.success(result);
      }
      return this.ctx.response.error('找不到该用户信息');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }
  // 用户注册
  async create(dataObj) {
    // 判断验证码
    // const verify = this.ctx.session.code;
    // console.log('verify ==>', verify);
    // if (verify && (verify.toLowerCase() !== dataObj.verify.toLowerCase())) {
    //   return this.ctx.response.error('验证码错误');
    // }

    try {
      const { User } = this.app.model.Tables.Shop;
      // 查找手机号码是否已经注册
      const isPhoneExit = await User.findOne({
        where: {
          phone: dataObj.phone,
        },
      });
      if (isPhoneExit) return this.ctx.response.error('手机号码已注册');

      // 查找姓名是否已经注册
      const isUserExit = await User.findOne({
        where: {
          name: dataObj.name,
        },
      });
      if (isUserExit) return this.ctx.response.error('用户名已存在');
      // 加密密码
      dataObj.password = await this.ctx.genHash(String(dataObj.password));
      const result = (await User.create(dataObj)).toJSON();
      delete result.password;

      return result
        ? this.ctx.response.success(result, '注册成功')
        : this.ctx.response.error(result, '注册失败');
    } catch (error) {
      console.log(error);
      return this.ctx.response.error(error.message);
    }
  }
  // 删除用户
  async destroy(id) {
    try {
      const { ctx } = this;
      const { User } = this.app.model.Tables.Shop;
      const result = User.destroy({
        where: {
          id,
        },
      });
      return result > 0
        ? ctx.response.success('删除成功')
        : ctx.response.error(result, '删除失败');
    } catch (error) {
      return this.ctx.response.error(error.message);
    }
  }

  async recharge(money) {
    const { ctx, app } = this;
    const { User } = app.model.Tables.Shop;
    const result = await User.findByPk(ctx.userInfo.id);
    const data = await result.update({
      money: result.dataValues.money + money,
    });
    return data
      ? ctx.response.success(data, '充值成功')
      : ctx.response.error(data, '充值失败');
  }

  async balance() {
    const { ctx, app } = this;
    const { User } = app.model.Tables.Shop;

    const result = await User.findByPk(ctx.userInfo.id);
    return result
      ? ctx.response.success({ money: result.dataValues.money }, '获取成功')
      : ctx.response.error(result, '获取失败');
  }
}

module.exports = UserService;
